package com.yangit.temp.util.pdf.test;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;

import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

public class ItextPDFUtil {

	public static void main(String[] args) {
		String path="E:\\北站测试.pdf";
		String outpath="E:\\test.pdf";
		Map root = new HashMap();
        root.put("name", "realName");
        root.put("file", "sn");
        root.put("name0", "realName");
        root.put("file0", "sn");
//        root.put("title", "title");
//        root.put("acceptResult", "acceptResult");
        
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        ItextPDFUtil.fillPdf(path, root, outpath);
        try {
           // FileUtil.fileDownload(response, PathUtil.getClasspath() + "yqh/" + id + ".pdf", "稿件邀请函.pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	
	
	
	public static void fillPdf(String filePath, Map<String, String> params, String outPath) {
        try {
            PdfReader reader = new PdfReader(filePath);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            PdfStamper ps = new PdfStamper(reader, bos);
            AcroFields s = ps.getAcroFields();
            // 给表单添加中文字体 这里采用系统字体。不设置的话，中文可能无法显示,这里全是英文，所以不用改成中文适应
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            s.addSubstitutionFont(bf);
            // 遍历data 给pdf表单表格赋值
            for (String key : params.keySet()) {
                    s.setField(key,params.get(key));
            }
            ps.setFormFlattening(true);
            ps.close();
            FileOutputStream fos = new FileOutputStream(outPath);
            fos.write(bos.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	
	
}
